package com.newer.textdbnotepad

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.newer.textdbnotepad.databinding.NoteDetailActivityBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class NoteDetailActivity : ComponentActivity() {
    private val viewModel: NoteDetailViewModel by viewModels()

    companion object {
        private const val EXTRA_NOTE_KEY = "noteId"

        fun launch(context: Context, noteKey: String) {
            val intent = Intent(context, NoteDetailActivity::class.java).apply {
                putExtra(EXTRA_NOTE_KEY, noteKey)
            }
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = NoteDetailActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.tvSave.setOnClickListener {
            viewModel.save(binding.etTitle.text.toString(), binding.etContent.text.toString())
        }

        viewModel.noteDetail.observe(this) {
            binding.etTitle.setText(it.noteTitle)
            binding.etContent.setText(it.noteContent)
        }

        lifecycleScope.launch {
            viewModel.shareFlow.collect {
                Toast.makeText(this@NoteDetailActivity, it, Toast.LENGTH_SHORT).show()
                finish()
            }
        }


        val key = intent.getStringExtra(EXTRA_NOTE_KEY) ?: return
        viewModel.getNote(key)

    }
}